package com.example.Project_Module.dao.impl.Impl;

import com.example.Project_Module.dao.UserDao;
import com.example.Project_Module.domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {

    JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    @Override
    public List<User> findAll() {
        return jdbcTemplate.query("select * from sys_user",new BeanPropertyRowMapper<User>(User.class));
    }

    @Override
    public Long save(User user) {
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement prepareStatement = connection.prepareStatement("insert into sys_user values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
                prepareStatement.setObject(1,null);
                prepareStatement.setObject(2,user.getUsername());
                prepareStatement.setObject(3,user.getEmail());
                prepareStatement.setObject(4,user.getPassword());
                prepareStatement.setObject(5,user.getPhoneNum());
                return prepareStatement;
            }
        };
//        创建keyholder
        GeneratedKeyHolder KeyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(creator,KeyHolder);
        long userId = KeyHolder.getKey().longValue();
        return userId;//返回当前保存用户id该id是数据库自动生成的
//        jdbcTemplate.update("insert into sys_user values(?,?,?,?,?)",null,user.getUsername(),user.getEmail(),user.getPassword(),user.getPhoneNum());
    }

    @Override
    public void saveUserRoleRel(Long userid, Long[] roleIds) {
        for (Long roleId:
             roleIds) {
            jdbcTemplate.update("insert into sys_user_role values (?,?)",userid,roleId);
        }

    }

    @Override
    public void del(Long userId) {
        jdbcTemplate.update("delete from sys_user where id = ?",userId);
    }

    @Override
    public void delUserRoleRel(Long userId) {
        jdbcTemplate.update("delete from sys_user_role where userId = ?",userId);
    }
}
